#include <iostream>
using std::cout;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() {}
    ListNode(int val, ListNode *next) : val(val), next(next) {}
};
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        if(head == nullptr || head->next == nullptr) return nullptr;
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast != nullptr && fast->next != nullptr)
        {
            slow = slow->next;
            fast = fast->next->next;

            if(slow == fast) // 相遇了
            {
                ListNode* index1 = head;
                ListNode* index2 = fast;
                while(1)
                {
                    if(index1 == index2)
                    {
                        return index1;
                    }
                    index1 = index1->next;
                    index2 = index2->next;
                }
            }
        }
        return nullptr;
    }
};

